import turtle
import pandas as pd
import time

# 步骤 2.1：Turtle基础绘图（简单图形）
def draw_basic_shapes():
    t = turtle.Turtle()
    t.speed(3)
    t.pensize(3)
    t.color("blue")
    for _ in range(4):
        t.forward(100)
        t.right(90)
    t.penup()
    t.goto(-150, -150)
    t.pendown()
    t.circle(50)
    turtle.mainloop()  # 保证窗口不关闭

# 步骤 2.2：模拟移动轨迹（直线、曲线、停止条件、记录轨迹）
def simulate_movement():
    screen = turtle.Screen()
    screen.title("人 vs 鳄鱼 轨迹模拟")
    person = turtle.Turtle()
    croc = turtle.Turtle()

    person.color("green")
    croc.color("red")
    person.shape("turtle")
    croc.shape("turtle")

    person.penup()
    croc.penup()
    person.goto(-200, -100)
    croc.goto(-200, 100)

    person.pendown()
    croc.pendown()

    person_trail = []
    croc_trail = []

    meet_flag = False
    for i in range(200):
        person.forward(2)
        croc.forward(2)
        croc.left(1)

        # 记录轨迹
        person_trail.append(person.pos())
        croc_trail.append(croc.pos())

        # 停止条件：距离小于20，模拟“接触”
        if person.distance(croc) < 20:
            print(f"人和鳄鱼在第 {i} 步相遇！")
            meet_flag = True
            break

    if not meet_flag:
        print("模拟结束，未相遇")

    turtle.done()  # 关闭Turtle窗口后保持显示

    # 保存轨迹为CSV
    df = pd.DataFrame({
        'person_x': [pos[0] for pos in person_trail],
        'person_y': [pos[1] for pos in person_trail],
        'croc_x': [pos[0] for pos in croc_trail],
        'croc_y': [pos[1] for pos in croc_trail]
    })
    df.to_csv("track_data.csv", index=False)
    print("运动轨迹已保存为 track_data.csv")

    turtle.mainloop()  # 保证窗口不关闭

# 步骤 2.3：读取轨迹CSV并动态可视化
def visualize_path():
    try:
        df = pd.read_csv("track_data.csv")
    except FileNotFoundError:
        print("请先运行 simulate_movement 生成 track_data.csv 文件")
        return
    screen = turtle.Screen()
    screen.title("轨迹回放")
    person = turtle.Turtle()
    croc = turtle.Turtle()

    person.color("green")
    croc.color("red")
    person.shape("circle")
    croc.shape("triangle")
    person.penup()
    croc.penup()

    for i in range(len(df)):
        person.goto(df['person_x'][i], df['person_y'][i])
        croc.goto(df['croc_x'][i], df['croc_y'][i])
        time.sleep(0.02)

    turtle.done()  # 保证窗口保持开启
    turtle.mainloop()  # 保证窗口不关闭

# === 以下为执行逻辑 ===
if __name__ == "__main__":
    # 通过注释/取消注释以下函数调用，分别运行不同实验
    # 实验2.1：基础绘图
    # draw_basic_shapes()

    # 实验2.2：模拟人与鳄鱼运动轨迹并保存
    simulate_movement()

    # 实验2.3：读取CSV数据并动态播放轨迹
    # visualize_path()
    pass